package com.qf.servlet;

import com.qf.pojo.Admin;
import com.qf.service.AdminService;
import com.qf.service.impl.AdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/*
* @WebServlet 注解---->被tomcat解析    注解 跟注释不一样的
*
*           <servlet>
                     <servlet-name>   就是当前类名
                     <servlet-class>
*           <servlet-mapping>
                <servlet-name>
                <url-pattern>
       注解的本质是一个接口

                  在注解中讲这些xxx()---->称为 "xxx属性"
* */

//用户登录后台的控制器
@WebServlet("/login")
public class LoginServlet extends HttpServlet {


    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //解决post中文乱码
        request.setCharacterEncoding("utf-8");
        //1)获取前台用户提交的参数
        String name = request.getParameter("name");
        String password = request.getParameter("password");

       // System.out.println(name+"---"+password) ;

        //封装管理实体
        Admin admin = new Admin() ;
        admin.setName(name) ;
        admin.setPassword(password) ;

        //调用业务层接口
        AdminService adminService = new AdminServiceImpl() ;
        Admin loginAdmin = adminService.isLogin(admin) ;

        if(loginAdmin!=null){
            //true 成功

            //用户登录成功之后,需要将用户的信息 存储session中(存储服务器)
            //通过请求对象获取HttpSession, 将用户存储到服务器端
            // HttpSession getSession();
            HttpSession session = request.getSession();

            session.setAttribute("admin",loginAdmin);


            //请求转发 到admin_index.jsp
            request.getRequestDispatcher("/admin/admin_index/admin_index.jsp").forward(request,response);

        }else{
            //请求转发login.jsp
            request.setAttribute("msg","用户名或者密码输入错误") ;
            request.getRequestDispatcher("/admin/login.jsp").forward(request,response);
        }


    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request,response);

    }
}
